require('dotenv').config();
const wx = require('./wxlist');
const http = require('http');
const hostname = process.env.IPHOST;
const port = process.env.PORT;
const redis = require('redis');
const client = redis.createClient(process.env.REDISPORT, process.env.REDISHOSTNAME);
const request = require('request');
const url = require('url');

client.on('error', err => {
  console.log('redis error: ' + err);
});

client.on('connect', () => {
  console.log('redis connected!');
});

const doget = (appidParam, secretParam, req, res) => {
  const url_parse = url.parse(req.url, true);
  const query = url_parse.query;
  let appid = appidParam || query.appid;
  let secret = secretParam || query.secret;

  if (!appid || !secret) {
    res.statusCode = 404;
    return res.end();
  }
  res.statusCode = 200;
  res.setHeader('Content-Type', 'application/json');
  client.get('wxtoken_' + appid, (rediserr, val) => {
    if (val) {
      console.log(val);
      res.end(val);
    } else {
      request.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`, (error, response, body) => {
        if (error) {
          res.end(`{"message": "请求wxtoken_access_token失败：${error}"}`);
        } else {
          let seconds = parseInt(JSON.parse(body)['expires_in']);
          console.log(seconds);
          client.set('wxtoken_' + appid, body, 'EX', seconds);
          return res.end(body);
        }
      });
    }
  });
};

const server = http.createServer((req, res) => {
  if (req.url.indexOf('/cgi-bin/token?') > -1) {
    doget(undefined, undefined, req, res);
  } else if (req.url.indexOf('/gettoken?') > -1) {
    const url_parse = url.parse(req.url, true);
    const query = url_parse.query;
    let wxname = query.name;
    if (!wxname) {
      res.statusCode = 404;
      return res.end();
    }
    let arr = [];
    for (let keys in wx) {
      if (wxname == keys) {
        arr = wx[wxname].split(' ');
      }
    }
    if (arr.length === 0) {
      res.statusCode = 404;
      return res.end();
    }
    doget(arr[0], arr[1], req, res);
  }
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
